package abel.wlmr.model.unit;

import abel.wlmr.model.WlmrBaseUnit;
import abel.wlmr.model.WlmrException;
import io.netty.buffer.ByteBuf;

public class Afn04F6768Unit extends WlmrBaseUnit {
    private static final short FIXED_LENGTH = 1;

    private static final byte START_FLAG = 0x55;
    private static final byte STOP_FLAG = (byte) 0xAA;

    private byte startStop;

    public Afn04F6768Unit() {
        super();
    }

    public Afn04F6768Unit(short guessedLen) {
        super(guessedLen);
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.AppUnitPart#appendBuf(io.netty.buffer.ByteBuf)
     */
    @Override
    public ByteBuf appendBuf(ByteBuf buf) {
        if (startStop != START_FLAG || startStop != STOP_FLAG) {
            throw new IllegalArgumentException("start-stop flag should be 0x55 or 0xAA");
        }

        buf.writeByte(startStop);

        return buf;
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.AppUnitPart#parseBuf(io.netty.buffer.ByteBuf)
     */
    @Override
    public int parseBuf(ByteBuf buf) throws WlmrException {
        if (buf.readableBytes() < FIXED_LENGTH) {
            return -1;
        }

        startStop = buf.readByte();
        if (startStop != START_FLAG || startStop != STOP_FLAG) {
            throw new WlmrException("start-stop flag should be 0x55 or 0xAA");
        }

        return getGuessedLength();
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.WlmrDataPart#getMinLength()
     */
    @Override
    public int getMinLength() {
        return FIXED_LENGTH;
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.WlmrDataPart#getFinalLen()
     */
    @Override
    public short getFinalLen() {
        return FIXED_LENGTH;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("{startStop:%s}", startStop);
    }

    /**
     * @return the startStop
     */
    public byte getStartStop() {
        return startStop;
    }

    /**
     * @param startStop
     *            the startStop to set
     */
    public void setStartStop(byte startStop) {
        this.startStop = startStop;
    }

}
